<template>
	<view class="container">
		<Navigator2 :title="$t('me.accountInfo')"></Navigator2>
		<view class="content">
			<!-- 头像设置 -->
			<view class="info-group">
				<view class="info-item" @click="showAvatarOptions">
					<text class="label">{{ $t('me.avatar') }}</text>
					<view class="right-content">
						<image
							class="avatar"
							:src="avatar ? avatar : '/static/me_man.png'"
							@error="onAvatarError"
							@load="onAvatarLoad"
						></image>
						<image class="arrow" src="/static/me_rightcursor.png"></image>
					</view>
				</view>
			</view>
			
			<!-- 昵称和手机号 -->
			<view class="info-group">
				<view class="info-item" @click="toEditNickname">
					<text class="label">{{ $t('me.nickname') }}</text>
					<view class="right-content">
						<text class="value">{{ username }}</text>
						<image class="arrow" src="/static/me_rightcursor.png"></image>
					</view>
				</view>
				
				<view class="info-item">
					<text class="label">{{ $t('me.loginPhone') }}</text>
					<text class="value">{{ phone }}</text>
				</view>
			</view>
		</view>
		
		<!-- 头像选择菜单 -->
		<uni-popup ref="avatarPopup" type="bottom" :isMaskClick="true" backgroundColor="#FFFFFF" maskBackgroundColor="rgba(0, 0, 0, 0.4)">
			<view class="avatar-options-container">
				<view class="avatar-options-group">
					<view class="avatar-option">{{ $t('me.uploadAvatar') }}</view>
					<view class="avatar-option" @click="takePhoto">{{ $t('me.takePhoto') }}</view>
					<view class="avatar-option" @click="chooseFromAlbum">{{ $t('me.chooseFromAlbum') }}</view>
				</view>
				<view class="avatar-cancel-group">
					<view class="avatar-cancel" @click="hideAvatarOptions">{{ $t('me.cancel') }}</view>
				</view>
			</view>
		</uni-popup>

		<!-- 图片裁剪组件 -->
		<AvatarCropper
			:show="showCropper"
			:imagePath="selectedImagePath"
			:compress="true"
			:quality="0.8"
			:maxSize="800"
			@confirm="onCropConfirm"
			@cancel="onCropCancel"
		/>
	</view>
</template>

<script>
	import api from '@/js/api'
	import util from '@/js/util'
	import Navigator2 from '@/components/Navigator2.vue'
	import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
	import AvatarCropper from '@/components/AvatarCropper.vue'
	export default {
		data() {
			return {
				username: '',
				phone: '',
				avatar: '',
				// 裁剪相关
				showCropper: false,
				selectedImagePath: ''
			}
		},
		onShow() {
			console.log('onShow,', uni.getStorageSync('userInfo'))
			const userInfo = uni.getStorageSync('userInfo')
			if (userInfo) {
				this.username = userInfo.username
				this.phone = util.desensitizePhone(userInfo.phone)
				// 添加时间戳避免图片缓存问题
				this.avatar = userInfo.avatar ? userInfo.avatar + '?t=' + Date.now() : ''
			}
		},
		methods: {
			toEditNickname() {
				uni.navigateTo({
					url: '/pages/me/editenickname'
				})
			},
			showAvatarOptions() {
				this.$refs.avatarPopup.open()
			},
			hideAvatarOptions() {
				this.$refs.avatarPopup.close()
			},
			takePhoto() {
				this.hideAvatarOptions()
				// 调用相机拍照
				uni.chooseImage({
					count: 1,
					sourceType: ['camera'],
					success: (res) => {
						console.log('拍照结果:', res)
						// 进入裁剪界面
						this.selectedImagePath = res.tempFilePaths[0]
						this.showCropper = true
					}
				})
			},
			chooseFromAlbum() {
				this.hideAvatarOptions()
				// 从相册选择
				uni.chooseImage({
					count: 1,
					sourceType: ['album'],
					success: (res) => {
						console.log('相册选择结果:', res)
						// 进入裁剪界面
						this.selectedImagePath = res.tempFilePaths[0]
						this.showCropper = true
					}
				})
			},

			// 裁剪确认
			onCropConfirm(croppedImagePath) {
				this.showCropper = false

				// 显示上传中提示
				uni.showLoading({
					title: '上传中...'
				})

				// 上传裁剪后的图片
				api.uploadFile(croppedImagePath, uni.getStorageSync('userInfo').id).then(res => {
					uni.hideLoading()
					console.log('上传原始结果:', res)

					// 解析返回的 JSON 字符串
					let result
					try {
						result = typeof res === 'string' ? JSON.parse(res) : res
					} catch (e) {
						console.error('解析上传结果失败:', e)
						result = { code: 500, message: '数据解析失败' }
					}

					console.log('解析后结果:', result)

					if (result.code == 200) {
						// 更新本地存储
						const userInfo = uni.getStorageSync('userInfo')
						userInfo.avatar = result.data
						uni.setStorageSync('userInfo', userInfo)

						// 强制更新头像显示，添加时间戳避免缓存
						const newAvatarUrl = result.data + '?t=' + Date.now()
						this.avatar = newAvatarUrl

						console.log('新头像URL:', newAvatarUrl)

						// 强制页面重新渲染
						this.$forceUpdate()

						uni.showToast({
							title: '头像更新成功',
							icon: 'success'
						})
					} else {
						uni.showToast({
							title: result.message || result.msg || '上传失败',
							icon: 'none'
						})
					}
				}).catch(err => {
					uni.hideLoading()
					console.log('上传失败:', err)
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
				})
			},

			// 裁剪取消
			onCropCancel() {
				this.showCropper = false
				this.selectedImagePath = ''
			},

			// 头像加载成功
			onAvatarLoad() {
				console.log('头像加载成功:', this.avatar)
			},

			// 头像加载失败
			onAvatarError(e) {
				console.log('头像加载失败:', e, this.avatar)
				// 加载失败时使用默认头像
				this.avatar = '/static/me_man.png'
			}
		},
		components: {
			Navigator2,
			'uni-popup': uniPopup,
			AvatarCropper
		}
	}
</script>

<style lang="scss">
/* 全局样式 */
page {
	background-color: #F1F2F5;
}
</style>

<style lang="scss" scoped>
.container {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: #F1F2F5;
	
	.content {
		padding: 16px;
		
		.info-group {
			margin-bottom: 16px;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.info-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				background-color: #FFFFFF;
				padding: 20px;
				margin-bottom: 1px;
				
				&:first-child {
					border-radius: 8px 8px 0 0;
				}
				
				&:last-child {
					border-radius: 0 0 8px 8px;
					margin-bottom: 0;
				}
				
				&:only-child {
					border-radius: 8px;
				}
			}
		}
		
		.label {
			font-size: 16px;
			color: #1F2937;
		}
		
		.right-content {
			display: flex;
			align-items: center;
			
			.avatar {
				width: 30px;
				height: 30px;
				border-radius: 20px;
				margin-right: 12px;
				background-color: #F7F9FC;
			}
			
			.value {
				font-size: 16px;
				color: #6B7280;
				margin-right: 12px;
			}
			
			.arrow {
				width: 8px;
				height: 14px;
				flex-shrink: 0;
			}
		}
		
		.value {
			font-size: 16px;
			color: #6B7280;
		}
		
		.avatar-options-container {
			padding: 10px;
			
			.avatar-options-group {
				background-color: #FFFFFF;
				border-radius: 12px;
				margin-bottom: 8px;
				overflow: hidden;
				
				.avatar-option {
					padding: 20px;
					text-align: center;
					font-size: 16px;
					color: #007AFF;
					border-bottom: 1px solid #E5E5E5;
					
					&:last-child {
						border-bottom: none;
					}
					
					&:active {
						background-color: #F0F0F0;
					}
				}
			}
			
			.avatar-cancel-group {
				background-color: #FFFFFF;
				border-radius: 12px;
				overflow: hidden;
				
				.avatar-cancel {
					padding: 20px;
					text-align: center;
					font-size: 16px;
					color: #FF3B30;
					font-weight: 600;
					
					&:active {
						background-color: #F0F0F0;
					}
				}
			}
		}
	}
}
</style>

<style lang="scss">

/* 覆盖avatar选项的padding */
.avatar-options-container {
	font-size: #14161A !important;
	font-size: 16px !important;
	.avatar-options-group {
		.avatar-option {
			padding: 16px !important;
			text-align: center !important;
			border-bottom: 1px solid #E5E5E5 !important;

			&:active {
				background-color: #F0F0F0;
			}
		}

		.avatar-option:first-child {
			&:active {
				background-color: #FFFFFF;
			}
		}
	}
	
	.avatar-cancel-group {
		.avatar-cancel {
			padding: 16px !important;
			text-align: center !important;

			&:active {
				background-color: #F0F0F0;
			}
		}
	}
}
</style>
